package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.service.MemberService;
import com.itheima.health.service.OrderService;
import com.itheima.health.service.ReportService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 数据报告控制器
 */
@RestController
@RequestMapping("/report")
@Slf4j
public class ReportController {
//修改版
    @DubboReference
    private MemberService memberService;

    @DubboReference
    private OrderService orderService;


    @DubboReference
    private ReportService reportService;

    @GetMapping("/getMemberReport")
    public Result getMemberDataByDate(String startDate, String endDate) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
        long time1 = simpleDateFormat.parse(startDate).getTime();
        long time2 = simpleDateFormat.parse(endDate).getTime();
        Date date = new Date(time2 - time1);
        /*System.out.println(new Date(new Date().getTime()-new Date().getTime()).getYear());
        System.out.println(date.getYear());*/
        int i=0;
        if (date.getYear()==new Date(new Date().getTime()-new Date().getTime()).getYear()){
            i = date.getMonth() - new Date(new Date().getTime()-new Date().getTime()).getMonth();
            //System.out.println(i);
        }else {
            int i1 = date.getYear() - new Date(new Date().getTime() - new Date().getTime()).getYear();
            i = date.getMonth() - new Date(new Date().getTime()-new Date().getTime()).getMonth();
            i=i1*12+i;
        }
        Calendar instance = Calendar.getInstance();
        instance.setTime(simpleDateFormat.parse(startDate));
        ArrayList<String> months = new ArrayList<>();
        for (int i1 = 0; i1 < i; i1++) {
            months.add(simpleDateFormat.format(instance.getTime()));
            instance.add(Calendar.MONTH,1);
        }
        HashMap<String, List> hashMap=null;
        try {
            hashMap = new HashMap<>();
            List<Long> map=reportService.getTimeCountByTime(months);
            hashMap.put("months",months);
            hashMap.put("memberCount",map);
        } catch (Exception e) {
        }
        return new Result(true, MessageConst.GET_MEMBER_NUMBER_REPORT_SUCCESS,hashMap);
    }

    @GetMapping("/getSetmealReport")
    public Result getSetmealReport(){

//        List<Map<String,Object>> setmealCount = Arrays.asList(
//                    new HashMap<String,Object>(){{put("name","套餐1");put("value",10);}},
//                    new HashMap<String,Object>(){{put("name","套餐2");put("value",10);}},
//                   new HashMap<String,Object>(){{put("name","套餐3");put("value",10);}}
//        );
        List<Map<String,Object>> setmealCount = orderService.countBySetmeal();


//        List<String> setmealNames = new ArrayList<>();
//        for (Map<String, Object> map : setmealCount) {
//            setmealNames.add(String.valueOf(map.get("name")));
//        }
        List<String> setmealNames = setmealCount.stream().map(e -> (String) e.get("name")).collect(Collectors.toList());

        // 构造返回结构
        Map<String,Object> map = new HashMap<>();
        map.put("setmealNames",setmealNames);
        map.put("setmealCount",setmealCount);

        return  new Result(true,MessageConst.GET_SETMEAL_COUNT_REPORT_SUCCESS,map);
    }


    @GetMapping("/getBusinessReportData")
    public Result getBusinessReportDate(){
        Map<String ,Object> map = reportService.getBusinessReprotData();
        return  new Result(true,MessageConst.GET_BUSINESS_REPORT_SUCCESS,map);
    }


    @GetMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletResponse response){

        // 获取数据
        Map<String, Object> reportData = reportService.getBusinessReprotData();
        log.debug("[导出运营数据报表]rpc rsp:{}", reportData);

        // 取出返回结果
        String reportDate = (String) reportData.get("reportDate");
        // 获取会员相关数据
        Long todayNewMember = (Long) reportData.get("todayNewMember");
        Long thisWeekNewMember = (Long) reportData.get("thisWeekNewMember");
        Long thisMonthNewMember = (Long) reportData.get("thisMonthNewMember");
        Long totalMember = (Long) reportData.get("totalMember");
        // 获取预约相关数据
        Long todayOrderNumber = (Long) reportData.get("todayOrderNumber");
        Long thisWeekOrderNumber = (Long) reportData.get("thisWeekOrderNumber");
        Long thisMonthOrderNumber = (Long) reportData.get("thisMonthOrderNumber");
        // 获取到诊相关数据
        Long todayVisitsNumber = (Long) reportData.get("todayVisitsNumber");
        Long thisWeekVisitsNumber = (Long) reportData.get("thisWeekVisitsNumber");
        Long thisMonthVisitsNumber = (Long) reportData.get("thisMonthVisitsNumber");
        // 获取套餐数据
        List<Map> hotSetmeal = (List<Map>) reportData.get("hotSetmeal");


        try(InputStream is = ReportController.class.getClassLoader().getResourceAsStream("report_template.xlsx");
            ServletOutputStream os = response.getOutputStream();
            ) {
            // 构建excel（包含运营数据）
            Workbook workbook = new XSSFWorkbook(is);

            // 填入数据
            Sheet sheet = workbook.getSheetAt(0);
            sheet.getRow(2).getCell(5).setCellValue(reportDate);
            // 会员数据
            sheet.getRow(4).getCell(5).setCellValue(todayNewMember);
            sheet.getRow(4).getCell(7).setCellValue(totalMember);
            sheet.getRow(5).getCell(5).setCellValue(thisWeekNewMember);
            sheet.getRow(5).getCell(7).setCellValue(thisMonthNewMember);
            //预约数据
            sheet.getRow(7).getCell(5).setCellValue(todayOrderNumber);
            sheet.getRow(7).getCell(7).setCellValue(todayVisitsNumber);
            sheet.getRow(8).getCell(5).setCellValue(thisWeekOrderNumber);
            sheet.getRow(8).getCell(7).setCellValue(thisWeekVisitsNumber);
            sheet.getRow(9).getCell(5).setCellValue(thisMonthOrderNumber);
            sheet.getRow(9).getCell(7).setCellValue(thisMonthVisitsNumber);
            // 热门套餐
            int rowNum = 12;
            for (Map map : hotSetmeal) {
                // 填入数据
                sheet.getRow(rowNum).getCell(4).setCellValue((String) map.get("name"));//套餐名称
                sheet.getRow(rowNum).getCell(5).setCellValue((Long)map.get("setmeal_count"));//预约数量
                sheet.getRow(rowNum).getCell(6).setCellValue(((BigDecimal)map.get("proportion")).doubleValue());//套餐占比
                // 行号+1
                rowNum++;
            }

            // 指定数据类型
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition","attachment;fileName=report_"+reportDate+".xlsx");
            // 下载
            workbook.write(os);
            // 清空缓冲区
            os.flush();

        } catch (IOException e) {
           log.error("",e);
           return new Result(false,MessageConst.GET_BUSINESS_REPORT_FAIL);
        }
        return  new Result(true,MessageConst.GET_BUSINESS_REPORT_SUCCESS);
    }

    @GetMapping("/getMemberSex")
    public Result getMemberSexReport(){
        List<Map<String,Double>> memberCount=memberService.countByMember();
        return new Result(true,MessageConst.GET_MEMBER_NUMBER_REPORT_SUCCESS,memberCount);
    }
    @GetMapping("/getMemberAge")
    public Result getMemberAge(){
        try {
            List<Map<String, Object>> ageBand = memberService.countByAge();
            return new Result(true,MessageConst.GET_MEMBER_NUMBER_REPORT_SUCCESS,ageBand);
        } catch (ParseException e) {
            e.printStackTrace();
            return new Result(false,MessageConst.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }
}
